import { ScrollView, StyleSheet, Text, View, Button, TouchableOpacity, RefreshControl, Dimensions, TouchableWithoutFeedback } from 'react-native'
import React, { useCallback, useRef, useMemo, useState } from 'react'
import BottomSheet, { BottomSheetScrollView } from "@gorhom/bottom-sheet";
import analyticsData from "../charts/assets/analyticsData";
import BoxCard from '../components/BoxCard'
import Line from '../charts/Line';
import TitleBox from '../components/TitleBox';
import DataBox from '../components/DataBox';
import { AntDesign } from '@expo/vector-icons';
import axios from 'axios';
const { width, height } = Dimensions.get('window')
base = "http://192.168.43.57:8088/"

const options = {
    method: "POST",
    url: base + "analyze_house_price_change"
};
const Prediction = () => {

    const [areaname, setareaname] = useState('渝北');
    const [commname, setcommname] = useState('中央公园');
    const [qx_house_price, setqx_house_price] = useState(null);
    const [qx_growth_rate, setqx_growth_rate] = useState(null);
    const [qy_house_price, setqy_house_price] = useState(null);
    const [qy_growth_rate, setqy_growth_rate] = useState(null);
    const [spinning, setSpinning] = useState(false);
    const snapPoints = useMemo(() => ["25%", "50%", "90%"], []);

    // 定义区县列表
    const AreaList = useMemo(
        () =>
            analyticsData.cq_area_comm_data
                .map((item, index) => `${item.value}`),
        []
    );
    // 定义区域列表
    const CountryList = useMemo(
        () =>
            findAreaByLabel(analyticsData.cq_area_comm_data, areaname).children
                .map((item, index) => `${item.value}`),
        [areaname]
    );
    // 处理数组及children
    function findAreaByLabel(area, area_name) {
        return area.find(function (element) {
            return element.label === area_name;
        });
    }
    // 弹出BottomSheet
    const OpenBottomSheet = () => {
        handleSnapPress(0)
    }
    // 关闭BottomSheet
    const CloaseBottomSheet = () => {
        handleClosePress()
    }
    // 加载详细信息
    function GetDetailData(data) {
        console.log('data:', data)
        setSpinning(true);
        Object.assign(options, data)
        console.log('options:', options)
        axios.request(options).then((response) => {
            console.log(response.data)
            setqx_house_price(response.data.data.qx_house_price)
            setqy_house_price(response.data.data.qy_house_price)
            setqx_growth_rate(response.data.data.qx_growth_rate)
            setqy_growth_rate(response.data.data.qy_growth_rate)
            setSpinning(false);
            if (response.status == 200) {
                CloaseBottomSheet()
            }
        });
    }
    // hooks
    const sheetRef = useRef(null);

    // variables
    const data = useMemo(
        () =>
            Array(50)
                .fill(0)
                .map((_, index) => `index-${index}`),
        []
    );

    // callbacks
    const handleSheetChange = useCallback((index) => {
        console.log("handleSheetChange", index);
    }, []);
    const handleSnapPress = useCallback((index) => {
        sheetRef.current?.snapToIndex(index);
    }, []);
    const handleClosePress = useCallback(() => {
        sheetRef.current?.close();
    }, []);

    // 区域render
    const renderItem = (item) => (
        <TouchableOpacity onPress={() => { console.log('Item clicked:', item, findAreaByLabel(analyticsData.cq_area_comm_data, item).children), setareaname(item) }} key={item} style={styles.itemContainer}>
            <Text>{item}</Text>
        </TouchableOpacity>
    );
    // 小区render
    const renderCountryItem = (item) => {
        const { code } = item;
        return (
            <TouchableOpacity onPress={() => { console.log('Item clicked:', item); GetDetailData({ data: { area: areaname, comm: item }, headers: { "content-type": "application/x-www-form-urlencoded" }, }); setcommname(item) }} key={'Country' + item + Math.random(0, 10)} style={styles.itemContainer}>
                <Text>{item}</Text>
            </TouchableOpacity>
        );
    };
    return (
        <>
            <ScrollView
                style={{
                    flex: 1
                }}
                refreshControl={
                    <RefreshControl
                        refreshing={spinning}
                        colors={['#887ef2']} // 设置colors属性（Android）
                        tintColor="#887ef2" // 设置tintColor属性（iOS）
                    />
                }
            >
                <TouchableWithoutFeedback
                    onPress={() => OpenBottomSheet()}
                >
                    <View
                        style={
                            styles.TopSelBox
                        }
                    >
                        <View style={styles.TopBox}>
                            <Text style={{ fontSize: 12 }}>{`${areaname}/${commname}`}</Text>
                            <AntDesign name="down" size={12} color="black" />
                        </View>
                    </View>
                </TouchableWithoutFeedback>
                {qx_house_price ? (
                    <BoxCard>
                        <TitleBox title={`${areaname}近十年房价变化`} label={`${qx_house_price.labels[qx_house_price.labels.length - 2]}至${qx_house_price.labels[qx_house_price.labels.length - 1]}`}></TitleBox>
                        <Line series={qx_house_price.series} labels={qx_house_price.labels} title={`${areaname}近十年房价趋势`}></Line>
                    </BoxCard>
                ) : (
                    <></>
                )}
                {qy_growth_rate ? (
                    <BoxCard>
                        <TitleBox title={`房价指标情况`} label={`${qx_house_price.labels[qx_house_price.labels.length - 2]}至${qx_house_price.labels[qx_house_price.labels.length - 1]}`}></TitleBox>
                        <View style={styles.rateBox}>
                            <DataBox title="季度环比" data={qx_house_price.series[qx_house_price.series.length - 1]} unit="元" rate={qx_growth_rate[0]}></DataBox>
                            <DataBox title="年度同期" data={qx_house_price.series[qx_house_price.series.length - 1]} unit="元" rate={qx_growth_rate[1]}></DataBox>
                            <DataBox title="年度环比" data={qx_house_price.series[qx_house_price.series.length - 1]} unit="元" rate={qx_growth_rate[2]}></DataBox>
                        </View>
                    </BoxCard>
                ) : (
                    <></>
                )}
                {qy_house_price ? (
                    <BoxCard>
                        <TitleBox title={`${commname}近期房价变化`} label={`${qy_house_price.labels[qy_house_price.labels.length - 2]}至${qy_house_price.labels[qy_house_price.labels.length - 1]}`}></TitleBox>
                        <Line series={qy_house_price.series} labels={qy_house_price.labels} title={`${commname}近十年房价趋势`}></Line>
                    </BoxCard>
                ) : (
                    <></>
                )}
                {qy_growth_rate ? (
                    <BoxCard>
                        <TitleBox title={`房价指标情况`} label={`${qy_house_price.labels[qy_house_price.labels.length - 2]}至${qy_house_price.labels[qy_house_price.labels.length - 1]}`}></TitleBox>
                        <View style={styles.rateBox}>
                            <DataBox title="季度环比" data={qy_house_price.series[qy_house_price.series.length - 1]} unit="元" rate={qy_growth_rate[0]}></DataBox>
                            <DataBox title="年度同期" data={qy_house_price.series[qy_house_price.series.length - 1]} unit="元" rate={qy_growth_rate[1]}></DataBox>
                            <DataBox title="年度环比" data={qy_house_price.series[qy_house_price.series.length - 1]} unit="元" rate={qy_growth_rate[2]}></DataBox>
                        </View>
                    </BoxCard>
                ) : (
                    <></>
                )}
            </ScrollView>

            {/* 弹出层 */}
            <BottomSheet
                ref={sheetRef}
                index={1}
                snapPoints={snapPoints}
                onChange={handleSheetChange}
                enablePanDownToClose={true}
                handleIndicatorStyle={{ backgroundColor: '#887ef2' }}
            >
                <BottomSheetScrollView contentContainerStyle={styles.contentContainer}>
                    <ScrollView
                        style={{
                            width: '50%',
                            flex: 1
                        }}
                    >
                        {AreaList.map(renderItem)}
                    </ScrollView>
                    {/* <View style={{ width: 1, backgroundColor: '#000000', flex: 1, left: '50%' }}>

                    </View> */}
                    <ScrollView
                        style={{
                            width: '50%',
                            flex: 1
                        }}
                    >
                        {CountryList.map((item) => renderCountryItem(item))}
                    </ScrollView>
                </BottomSheetScrollView>
            </BottomSheet>
        </>
    )
}

export default Prediction

const styles = StyleSheet.create({
    contentContainer: {
        backgroundColor: "white",
        display: 'flex',
        flexDirection: 'row'
    },
    itemContainer: {
        padding: 6,
        margin: 6,
        backgroundColor: '#e7e5fc',
        borderRadius: 5
    },
    TopSelBox: {
        padding: 14,
        backgroundColor: '#fff',
        // display: 'flex',
        // flexDirection: 'row',
        // justifyContent: 'space-between'
    },
    TopBox: {
        width: width - 28,
        paddingHorizontal: 6,
        height: 30,
        backgroundColor: '#f7f7f7',
        borderRadius: 5,
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        flexDirection: 'row'
    },
    rateBox: {
        display: 'flex',
        flexDirection: 'row',
        flexWrap: 'wrap',
        width: width - 28
        // justifyContent: 'space-evenly'
    }
})